package com.springcloud.example;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
public class Controoler1 {


    /** 下载用户导入模板
     * @param file
     * @return
     * stats:importUsers
     */
    @GetMapping("/downloadTemplate")
    public void downloadTemp(HttpServletRequest request, HttpServletResponse response){
        //定义变量
        String downPath = "";
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = null;
        byte[] buffer = new byte[1024];
        InputStream inputStream = null;
        BufferedInputStream bis = null;
        OutputStream os = null; //输出流
        try {
            //获取resource中的文件，并生成流信息
            resource = resourceLoader.getResource("classpath:data/1.xlsx");
            inputStream = resource.getInputStream();
            //设置返回文件信息
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("userTemplate.xlsx","UTF-8"));
            //将内容使用字节流写入输出流中
            os = response.getOutputStream();
            bis = new BufferedInputStream(inputStream);
            while(bis.read(buffer) != -1){
                os.write(buffer);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流信息
            try {
                if(inputStream !=null ) {
                    inputStream.close();
                }
                if(bis != null) {
                    bis.close();
                }
                if(os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
